
import { http } from '@/utils/http'
import type { WorkflowParams } from '@/types/app'
import type { GenerateTask } from '@/types/app'

/**
 * 获取工作流列表
 */
export const getWorkflowParamsAPI = (workflowId: string) => {
    return http<WorkflowParams>({
      method: 'GET',
      url: `/cy/workflows/${workflowId}/params`,
    })
  }

  export const generateImageAPI = (data: Record<string, any>) => {
    let filePath = ''
    const formData: any = {}
  
    // 1. 提取图片和其它参数
    Object.entries(data).forEach(([key, value]) => {
      if (key === 'image_file' && value) {
        filePath = value // 这是 chooseImage 得到的本地路径
      } else if (key === 'params' && typeof value === 'object') {
        // 如果有复杂参数对象，转成字符串
        formData.params = JSON.stringify(value)
      } else {
        formData[key] = value
      }
    })
    console.log('formData:',formData)
    return new Promise<{ taskId: string }>((resolve, reject) => {
      uni.uploadFile({
        url: '/queue/generate',
        filePath,
        name: 'image', // 必须和后端 @RequestPart("image") 一致
        formData,
        // header: { 'Authorization': 'Bearer xxx' } // 一般由拦截器自动加
        success: (res: UniApp.UploadFileSuccessCallbackResult) => {
          try {
            const result = JSON.parse(res.data)
            if (result.code === 0) {
              resolve(result.result)
            } else {
              reject(new Error(result.msg || '请求失败'))
            }
          } catch (error) {
            reject(new Error('响应解析失败'))
          }
        },
        fail: (error: UniApp.GeneralCallbackResult) => {
          reject(new Error(error.errMsg || '上传失败'))
        }
      })
    })
  }

  export const checkTaskStatusAPI = (taskId: string) => {
    return http<GenerateTask>({
      method: 'GET',
      url: `/queue/checktaskstatus?taskId=${taskId}`,
    })
  }

  export const getUserTaskHistoryAPI = (page: number, size: number) => {
    return http<GenerateTask>({
      method: 'GET',
      url: '/queue/user-tasks/history',
      data:{
        page,
        size
      }
    })
  }